package com.dingup.paike.handler;


import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wancheng on 2018/10/18.
 */

@ControllerAdvice//所谓加强Controller就是@ControllerAdvice注解，有这个注解的类中的方法的某些注解会应用到所有的Controller里，其中就包括@ExceptionHandler注解。
@ResponseBody//REST风格接口
public class BindExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(BindExceptionHandler.class);

    @ExceptionHandler(value = BindException.class)
//异常处理(@ControllerAdvice注解注释的controller层和此注解注释的方法,会对所有controller层抛出的异常进行统一处理)
    public Map ExceptionHandler(HttpServletRequest request, Exception e) {
        BindException ex = (BindException) e;
        List<ObjectError> allErrors = ex.getAllErrors();//捕获的所有错误对象
        ObjectError error = allErrors.get(0);
        String defaultMessage = error.getDefaultMessage();//异常内容
        String url = request.getRequestURI();
        Map<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("message", defaultMessage);
        map.put("url", url);
        logger.info("BindException details={}", JSON.toJSONString(map));
        return map;
    }

}
